<?php

class RM_Module_PickupDropoff extends RM_Module implements RM_Others_Interface, RM_Search_Advanced_Interface, RM_Unit_Details_Tray_Interface, RM_Unit_List_Tray_Interface {
    /**
     * This string is for rm_reservation_summary table
     */
    const SUMMARY_TYPE = 'pickupdropoff';

    public function __construct() {
        $this->name = 'PickupDropoff';
    }

    /**
     * Returns all unit ids that are passed criteria option
     *
     * @param RM_Unit_Search_Criteria $criteria
     * @return array, false
     */
    function getAdvancedSearchUnitIDs(RM_Unit_Search_Criteria $criteria) {
        if (!$criteria->pickup || !$criteria->dropoff)
            return false;

        // get all the unit id's this is for when the amenities are set to 0
        $unitsModel = new RM_Units();
        $allUnits = $unitsModel->getAll(new RM_Unit_Search_Criteria())->toArray();
        foreach($allUnits as $allUnit){
            $allUnitArray[] = $allUnit['id'];
        }
        $allUnitsString = implode(",",$allUnitArray);

        $model = new RM_PickupDropoff();
        $pickupRow = $model->getLocationData($criteria->pickup)->toArray();
        $dropoffRow = $model->getLocationData($criteria->dropoff)->toArray();

        foreach ($pickupRow as $row) {
            if ($row['units'] !== ""){
                if ($row['units'] === '0'){
                    // all units selected
                    $units[] = $allUnitsString;
                } else {
                    $units[] = $row['units'];
                }
            }
        }
        foreach ($dropoffRow as $row) {
            if ($row['units'] !== "")
                if ($row['units'] === '0'){
                    // all units selected
                    $units[] = $allUnitsString;
                } else {
                    $units[] = $row['units'];
                }
        }

        $unitsString = implode(",", $units); // convert everything to comma seperated
        $unitsArray = explode(",", $unitsString); // convert everything to array
        $unitsArray = array_unique($unitsArray); // remove duplicates
        $unitsArray = array_filter($unitsArray, "is_numeric"); // filter only on numeric values

        return $unitsArray;
    }

    /**
     * This method will return node object for main admin menu tree.
     * Every child classes could overload this method to return any of the node object.
     * If there is no need to present a module in the main admin tree overloaded method should return NULL
     *
     * @return stdClass | null
     */
    public function getNode() {

        $std = new stdClass;
        $std->text = $this->getName();
        $std->id = 'system';
        $std->disabled = true;
        $std->expanded = 'true';
        $std->iconCls = "RM_modules_leaf_icon";
        $std->children = array();

        $locations = new stdClass;
        $locations->text = RM_Environment::getInstance()->getTranslation(RM_Environment::TRANSLATE_MAIN)->_('Admin.PickupDropoff.Main', 'Locations');
        $locations->id = $this->name . '_EditLocationsJson_NoAjax';
        $locations->leaf = 'true';
        $locations->iconCls = 'RM_modules_leaf_icon';
        $std->children[] = $locations;

        $prices = new stdClass;
        $prices->text = RM_Environment::getInstance()->getTranslation(RM_Environment::TRANSLATE_MAIN)->_('Admin.PickupDropoff.Main', 'Prices');
        $prices->id = $this->name . '_EditPricesJson_NoAjax';
        $prices->leaf = 'true';
        $prices->iconCls = 'RM_modules_leaf_icon';
        $std->children[] = $prices;

        return $std;
    }

    public function upgrade(){
        // userdata
        $moduleViewFolderPath = implode(DIRECTORY_SEPARATOR, array(
            RM_Environment::getConnector()->getRootPath(),
            'RM',
            'userdata',
            'modules',
            $this->name,
            'views',
            'user',
            'scripts',
            'Unit'
        ));

        $mainFolderPath = implode(DIRECTORY_SEPARATOR, array(
            RM_Environment::getConnector()->getRootPath(),
            'RM',
            'userdata',
            'views',
            'user',
            'scripts'
        ));

        $fileSource1 = implode(DIRECTORY_SEPARATOR, array($moduleViewFolderPath.DIRECTORY_SEPARATOR.'details','pickupdropoff_selectioninfo_details.phtml'));
        $fileDestin1 = implode(DIRECTORY_SEPARATOR, array($mainFolderPath.DIRECTORY_SEPARATOR.'Unit'.DIRECTORY_SEPARATOR.'details','pickupdropoff_selectioninfo_details.phtml'));
        $renameStatus1 = rename($fileSource1, $fileDestin1);

        $fileSource2 = implode(DIRECTORY_SEPARATOR, array($moduleViewFolderPath.DIRECTORY_SEPARATOR.'search','pickupdropoff_advancedsearch.phtml'));
        $fileDestin2 = implode(DIRECTORY_SEPARATOR, array($mainFolderPath.DIRECTORY_SEPARATOR.'Search'.DIRECTORY_SEPARATOR.'advanced','pickupdropoff_advancedsearch.phtml'));
        $renameStatus2 = rename($fileSource2, $fileDestin2);

    }

    /**
     * Install form designer panels
     */
    public function install() {
        parent::install();

        // userdata
        $moduleViewFolderPath = implode(DIRECTORY_SEPARATOR, array(
            RM_Environment::getConnector()->getRootPath(),
            'RM',
            'userdata',
            'modules',
            $this->name,
            'views',
            'user',
            'scripts',
            'Unit'
        ));

        $mainFolderPath = implode(DIRECTORY_SEPARATOR, array(
            RM_Environment::getConnector()->getRootPath(),
            'RM',
            'userdata',
            'views',
            'user',
            'scripts'
        ));

        $fileSource1 = implode(DIRECTORY_SEPARATOR, array($moduleViewFolderPath.DIRECTORY_SEPARATOR.'details','pickupdropoff_selectioninfo_details.phtml'));
        $fileDestin1 = implode(DIRECTORY_SEPARATOR, array($mainFolderPath.DIRECTORY_SEPARATOR.'Unit'.DIRECTORY_SEPARATOR.'details','pickupdropoff_selectioninfo_details.phtml'));
        $renameStatus1 = rename($fileSource1, $fileDestin1);

        $fileSource2 = implode(DIRECTORY_SEPARATOR, array($moduleViewFolderPath.DIRECTORY_SEPARATOR.'search','pickupdropoff_advancedsearch.phtml'));
        $fileDestin2 = implode(DIRECTORY_SEPARATOR, array($mainFolderPath.DIRECTORY_SEPARATOR.'Search'.DIRECTORY_SEPARATOR.'advanced','pickupdropoff_advancedsearch.phtml'));
        $renameStatus2 = rename($fileSource2, $fileDestin2);

        RM_Filesystem::deleteFolder($moduleViewFolderPath);
    }

    /**
     * removes any form designer panels
     */
    public function uninstall() {
        parent::uninstall();

        $file1 = implode(DIRECTORY_SEPARATOR, array(
            RM_Environment::getConnector()->getRootPath(),
            'RM',
            'userdata',
            'views',
            'user',
            'scripts',
            'Search',
            'advanced',
            'pickupdropoff_advancedsearch.phtml'
        ));
        RM_Filesystem::deleteFolder($file1);

        $file2 = implode(DIRECTORY_SEPARATOR, array(
            RM_Environment::getConnector()->getRootPath(),
            'RM',
            'userdata',
            'views',
            'user',
            'scripts',
            'Unit',
            'details',
            'pickupdropoff_selectioninfo_details.phtml'
        ));
        RM_Filesystem::deleteFolder($file2);
    }

    /**
     * Gets the HTML for the main unit details module tray icon
     *
     * @param RM_Unit_Row $unit
     * @return string
     */
    public function getHTML(RM_Unit_Row $unit) {

        return $this->_getIcon($unit, "large");
    }

    /**
     * Gets the HTML for the unit list module tray icon
     *
     * @param RM_Unit_Row $unit
     * @return string
     */
    public function getListHTML(RM_Unit_Row $unit) {

        return $this->_getIcon($unit, "small");
    }

    /**
     * private function called by getHTML and getListHTML and returns the HTML
     *
     * @param RM_Unit_Row $unit
     * @param string $iconSize
     * @return string
     */
    private function _getIcon($unit, $iconSize = "small") {

        $model = new RM_PickupDropoff();
        $locations = $model->getByUnitID($unit->id);

        if (count($locations) > 0) {
            $icon = RM_Environment::getConnector()->getRootURL() . 'RM/userdata/modules/PickupDropoff/images/tray_icon.gif';

            if ($iconSize == "small") {
                return "<a href='javascript:void(0)' onclick=\"RM_doShadowBox('" . RM_Environment::getInstance()->getRouter()->_('PickupDropoff', 'listlocations', array("unit_id" => $unit->id, "page" => "listlocations.phtml")) . "', '', 700, 400, 'iframe' )\" ><img width='30px' height='30px' src='" . $icon . "' border='0'></a>";
            } else {
                return "<a href='javascript:void(0)' onclick=\"RM_doShadowBox('" . RM_Environment::getInstance()->getRouter()->_('PickupDropoff', 'listlocations', array("unit_id" => $unit->id, "page" => "listlocations.phtml")) . "', '', 700, 400, 'iframe' )\" ><img src='" . $icon . "' border='0'></a>";
            }
        }
    }

    /**
     * Validate other selection for the user GUI
     *
     * @param array $data in format [other system name][unit id][other id] = user selected value for the other
     * @return bool
     */
    public function applySelection(Zend_Controller_Request_Abstract $request, RM_Reservation_Details $detail) {

        // pu/do store the selection in the criteria, so at this point we need
        // to get the criteria data then return it in the details object.
        $pudo = $this->getAllOthers();


        // assign the pudo to the details object
        $rowModel = new RM_PickupDropoff_Row(array("RM_ReservationPickupDropoff"));

        $otherObject = new RM_PickupDropoff_Object(
                        $rowModel,
                        $pudo->price,
                        1
        );
        $others[] = $otherObject;

        $detail->addOthers($others);
        return $detail;
    }

    /**
     * Assign extras to reservation
     *
     * @param RM_Reservation_Details $detail
     * @param RM_Reservation_Details_Row $detailRow
     * @return void
     */
    public function assign(RM_Reservation_Details $detail, RM_Reservation_Details_Row $detailRow) {

        $pudoModel = new RM_ReservationPickupDropoff();

        $other = $this->getAllOthers();

        $text = RM_Environment::getInstance()->getTranslation(RM_Environment::TRANSLATE_MAIN)->_('User.PickupDropoff.Main', 'name');

        $summaryModel = new RM_ReservationSummary();
        $summaryModel->insert(array(
            'row_id' => $detailRow->id,
            'type' => self::SUMMARY_TYPE,
            'reservation_detail_id' => $detailRow->id,
            'value' => 1,
            'total_amount' => $other->price,
            'name' => $text
        ));
        
        // insert into RM_ReservationPickupDropoff
        $dataArray = array("id"=>$detailRow->id,"id_pickup"=>$other->pickupID,"id_dropoff"=>$other->dropoffID);
        $pudoModel->insert($dataArray);
        
    }

    /**
     * Recalculate all for reservation, after some of the unit details has been changed
     *
     * @abstract
     * @param RM_Reservation_Row $reservation
     * @return bool
     */
    function recalculate(RM_Reservation_Row $reservation) {

    }

    /**
     * Returns extra HTML for a summary reservation page to present current system
     *
     * @abstract
     * @param RM_Reservation_Details $detail
     * @return string HTML code to paste
     */
    public function getSummary(RM_Reservation_Details $detail) {

        $request = RM_Environment::getConnector()->getRequestHTTP();
        $request->setControllerName('PickupDropoff');
        $request->setActionName('summary');
        $controller = new RM_User_PickupDropoffController(
                        $request,
                        new Zend_Controller_Response_Http()
        );
        $controller->setFrontController(Zend_Controller_Front::getInstance());
        $controller->view->unit = $detail->getUnit();

        $config = new RM_Config();
        $controller->view->currencySymbol = $config->getValue('rm_config_currency_symbol');

        $controller->view->pudoData = $this->getAllOthers();
        ;
        return $controller->view->render('PickupDropoff/summary.phtml');
    }

    /**
     * Returns the selected pickup/dropoff charges from the criteria
     *
     * @return object
     */
    function getAllOthers() {

        // others store their data in the criteria, this is just for ease
        $criteria = RM_Reservation_Manager::getInstance()->getCriteria();

        // get the data from the criteria then get the price
        $pudoPriceModel = new RM_PickupDropoffPrices();
        if (isset($criteria) && ($criteria->pickup && $criteria->dropoff)) {
            $pudoPrice = $pudoPriceModel->getPriceByLocationIDs($criteria->pickup, $criteria->dropoff);
            $pudoPrice = $pudoPrice['price'];
            $pickupID = $criteria->pickup;
            $dropoffID = $criteria->dropoff;

            $pudoModel = new RM_PickupDropoff();
            $pickupDetails = $pudoModel->getLocationData($pickupID)->toArray();
            $pickupDetails = $pickupDetails[0];
            $dropoffDetails = $pudoModel->getLocationData($dropoffID)->toArray();
            $dropoffDetails = $dropoffDetails[0];
        } else {
            $pudoPrice = 0;
            $pickupID = 0;
            $dropoffID = 0;
            $pickupDetails = array();
            $dropoffDetails = array();
        }

        // this method returns an object, this is used by model,
        // summary.phtml see pickup/dropoff's summary.phtml for an example

        $returnObject = new stdClass;
        $returnObject->name = $this->name;
        $returnObject->price = $pudoPrice;
        $returnObject->pickupID = $pickupID;
        $returnObject->pickupDetails = $pickupDetails;
        $returnObject->dropoffDetails = $dropoffDetails;
        $returnObject->dropoffID = $dropoffID;

        return $returnObject;
    }

    /**
     * This is a flexible method used for OtherSystems that insert or update
     *
     */
    public function updateOtherData($dataArray){
        // update or insert
        $model = new RM_ReservationPickupDropoff();

        try{
            // try to update
            $model->update($dataArray);
        } catch (Exception $e){
            // if it fails insert
            $model->insert($dataArray);
        }
    }

    /**
     * get the price based on locations
     */
    public function getPrice($data){

        $locationData = new stdClass;
        $locationData->id_pickup = $data['id_pickup'];
        $locationData->id_dropoff = $data['id_dropoff'];

        $priceModel = new RM_PickupDropoffPrices();
        $price = $priceModel->calculate($locationData);

        return $price;
    }
}